package com.roc.web.action.terminal;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.common.Excel2007TermFileProcessor;
import com.roc.common.FileProcessor;
import com.roc.page.BaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IExcelExportService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 
 * @author 陈锴
 * 
 * 终端序列号号段添加 
 * 
 * 2017-03-22
 *
 */

@Component
@Scope("prototype")
@Namespace("/terminalSnLeading")
public class TerminalSnLeadingAction extends BaseAction{
	
	private Logger logger=LogManager.getLogger(TerminalSnLeadingAction.class);
	
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	private File upload;
	
	private YjPosInfo posInfo;
	
	private String msg;
	
	private InputStream excelFile;
	private String exportExcelName;
	
	private InputStream downloadFile;
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	ITerminalService terminalService;

	@Autowired
	private IExcelExportService excelExportService;
	
	@Action(value = "terminalSnLeadingJsp", results = { @Result(name = "success", location = "/pages/terminal/terminal_sn_leading.jsp")
             })
	public String terminalSnLeadingJspAction() throws Exception{
		org();
		
/*		TblDictionaryItem itemBrand = new TblDictionaryItem();
		Map<String,String> brandMap = terminalService.selBrandItemByType(itemBrand);

		Map<String,String> modelMap=new TreeMap<String, String>();
		
		TblDictionaryItem item = new TblDictionaryItem();
		Map<String,String> typeMap = terminalService.selTypeItemByType(item);*/

		getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
		getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
		getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
		getRequest().setAttribute("assefMap", Utils.getSnAssefMap());
		
		return SUCCESS;
	}
	
	@Action(value = "terminalSnLeading", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = { 
			@Result(location = "/message.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")
	    })
	public String terminalSnLeadingAction() throws Exception{

		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		if(upload == null){
			addActionMessage("请选择文件");
			return SUCCESS;
		}
		try {
		//	org();
			
			FileProcessor processor = new Excel2007TermFileProcessor();
			List<YjPosInfo> posInfoImport = (List<YjPosInfo>) processor.process(upload);
			if(posInfoImport==null||posInfoImport.size()==0){
	        	addActionMessage("导入的Execl文件中不存在数据或文件格式不对，请确认!");
	        	return SUCCESS;
	        }
	        if(posInfoImport.size()>Constance.POS_SN_MAX_SIZE){
	        	addActionMessage("单批次导入最大记录为【"+Constance.POS_SN_MAX_SIZE+"】条，请分批导入！！！");
				return SUCCESS;
	        }
	        List<YjPosInfo> repeatList = getDeleteRepeatAgent(posInfoImport,posInfo);
	        if(repeatList!=null&&repeatList.size()>0){
	        	addActionMessage("导入的Execl文件中存在重复或sn号为空字符串或文字格式不对的记录，请确认!");
	        	getRequest().setAttribute("repeatList", repeatList);
	        	return SUCCESS;
	        }	
            repeatList= terminalService.batchSaveSeriaNum(posInfoImport, posInfo, loginOperators);
            if(repeatList!=null&&repeatList.size()>0){
            	addActionMessage("部分数据已成功导入，不再处理，详见列表!");
            	getRequest().setAttribute("repeatList", repeatList);
	        }	 
            addActionMessage("操作员【"+loginOperators.getAccountNo()+"】选择的文件中，总计【"+posInfoImport.size()+"】个，成功导入【"+(posInfoImport.size()-repeatList.size())+"】个，重复数量【"+repeatList.size()+"】");
            
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
	}

	// 导出excel
	@Action(value = "exportSNModel", results = {
			@Result(name = "success", type = "stream", params = { 
					"contentType", "application/octet-stream", "inputName",  
		            "downloadFile","contentDisposition",  "attachment;filename=${exportExcelName}.xlsx",
		            "bufferSize", "1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String exportSNModel() throws Exception {
		
		String reportName = "sn设备号下载模板";
		try {
			
			setExportExcelName(new String(reportName.getBytes(), "ISO8859-1"));
			
			logger.info("sn设备号模板下载");
		} catch (Exception e) {
			logger.error("导出sn设备号模板失败"+e.getMessage());
			addActionError(e.getMessage());
			return ERROR;
		}

		return SUCCESS;
	}
	/**
     * 去除重复终端序列号数据
     * @param list
     * @return
     */
	private List<YjPosInfo> getDeleteRepeatAgent(List<YjPosInfo> list,YjPosInfo baseInfo){
		List<YjPosInfo>  repeatList = new ArrayList<YjPosInfo>();
		Map<String,YjPosInfo> map = new HashMap<String,YjPosInfo>();
		try {
			for(YjPosInfo posInfo:list){
				if(posInfo.getSerialNum()!=null && !"".equals(posInfo.getSerialNum())){
					if((null == posInfo.getSerialNum().trim() || "".equals(posInfo.getSerialNum().trim())) 
							|| map.containsKey(posInfo.getSerialNum())
							|| (!Utils.checkSnCode(posInfo.getSerialNum().trim()))){// 校验sn序列号格式
						String brandCode = baseInfo.getPosBrand();
						String typeCode = baseInfo.getPosType();
						String nameCode = baseInfo.getPosName();
						
						posInfo.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
						posInfo.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
						posInfo.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
						
						posInfo.setAgentId(baseInfo.getAgentId());
						repeatList.add(posInfo);
						continue;
					}
					map.put(posInfo.getSerialNum(), posInfo);
				} else {
					// 如果为空
					String brandCode = baseInfo.getPosBrand();
					String typeCode = baseInfo.getPosType();
					String nameCode = baseInfo.getPosName();
					
					posInfo.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
					posInfo.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
					posInfo.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
					
					posInfo.setAgentId(baseInfo.getAgentId());
					repeatList.add(posInfo);
				}	
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		
		return repeatList;
	}
    
	//查询机构
	public void org() throws Exception{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	/*	TblInsInf inf = new TblInsInf();
		orgList=orgService.listOrg(inf);
*/
		// 如果登录账号为系统管理员，查询所有机构信息，且 分公司属性信息由 
		if ( logingOperators.getRoleType().equals(Role.SYSTEM.getCode()) ){

			orgList = orgService.queryAllOrgList();
		}else {
			TblInsInf tblInsInf = new TblInsInf();
			tblInsInf = orgService.queryOrgByOrgCode(logingOperators.getOrgCode());
			orgList.add(tblInsInf);
		}
	}


	public List<TblInsInf> getOrgList() {
		return orgList;
	}


	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public YjPosInfo getPosInfo() {
		return posInfo;
	}

	public void setPosInfo(YjPosInfo posInfo) {
		this.posInfo = posInfo;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExportExcelName() {
		return exportExcelName;
	}

	public void setExportExcelName(String exportExcelName) {
		this.exportExcelName = exportExcelName;
	}

	public InputStream getDownloadFile() {
		return ServletActionContext.getServletContext().getResourceAsStream("/model/exportSNModel.xlsx"); 
	}

	public void setDownloadFile(InputStream downloadFile) {
		this.downloadFile = downloadFile;
	}

}
